from django.shortcuts import render

# Create your views here.
from rest_framework import generics
from rest_framework import permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from know.util.JSONHttpResponse import JSONHttpResponse
from rest_framework.exceptions import NotFound
import json
import datetime
import logging
import hashlib

from know.serializers import UserListSerializer
from know.models import User
LOG_FILENAME = 'shop.log'

#logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO)


class CreateUser(APIView):
	"""创建编辑"""
	def post(self,request,format=None):
		name = request.data.get('name')
		pwd = request.data.get('pwd')
		id = request.data.get('id')
		md = hashlib.md5()
		md.update(str(pwd).encode(encoding='utf-8'))
		pwd = md.hexdigest()
		request.data['pwd'] = pwd
		if id:
			user = User.objects.get(pk=id)
			serializer = UserListSerializer(user,data=request.data)
			if serializer.is_valid():
				serializer.save()
				resp = {"errcode":0,"msg":"success"}
		else:
			serializer = UserListSerializer(data=request.data)
			try:
				user = User.objects.get(name=name)
			except Exception as e:
				if serializer.is_valid():
					serializer.save()
					resp = {"errcode":0,"msg":"success"}
				else:
					resp = {"errcode":1,"msg":"fail"}
			else:
				resp = {"errcode":2,"msg":"name is exist!"}
		return JSONHttpResponse(resp)
		
class Login(APIView):
	"""
	登录
	"""
	def post(self,request,format=None):
		name = request.data.get('name')
		pwd = request.data.get('pwd')
		try:
			user = User.objects.get(name=name)
		except Exception as e:
			resp = {"errcode":1,"msg": 'not exist'}
		else:
			md = hashlib.md5()
			md.update(str(pwd).encode(encoding='utf-8'))
			pwd = md.hexdigest()
			serializer = UserListSerializer(user)
			print(serializer.data)
			resp = {"errcode":0,"msg":"success"}
			if serializer.data.get('pwd') == pwd:
				resp = {"errcode":0,"msg":"success"}
			else:
				resp = {"errcode":3,"msg":"password is false"}
		finally:
			pass
		return JSONHttpResponse(resp)

class UserList(APIView):
	"""用户列表"""
	def post(self,request,format=None):
		userList = User.objects.all()
		print('ok')
		try:
			category = request.data.get("category")
		except Exception as e:
			resp = {"errcode":0}
			resp['data'] = userList
		else:
			resp = {"errcode":0}
			userList = userList.filter(category=category)
			serializer = UserListSerializer(userList,many=True)
			resp['data'] = serializer.data
		return JSONHttpResponse(resp)
		
class DeleteUser(APIView):
	def post(self,request,format=None):
		id = request.data.get("id")
		if id:
			try:
				user = User.objects.get(id=id)
			except Exception as e:
				resp = {"errcode":1, 'msg':'删除失败'}
			else:
				user.delete()
				resp = {"errcode":0}
		return JSONHttpResponse(resp)
			
